﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using SpreadsheetGear;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Planlama
{
    public partial class PastalBM : XForm
    {
        public PastalBM()
        {
            InitializeComponent();
        }

        public DataTable BOMLines;
        public DataSet Result;

        private void PastalBM_Load(object sender, EventArgs e)
        {
            Result = new DataSet();
            BOMLines = new DataTable();
            Result.Tables.Add(BOMLines);

            foreach (string s in "DosyaAdi,OrderName,Dagilim,Model,Aciklama,PLU,Color,Total,A01,A02,A03,A04,A05,A06,A07,A08,A09,A10,A11,A12,A13,A14,A15,Uretici,Artikel,KumasYonu".Split(",".ToCharArray()))
                BOMLines.Columns.Add(s, typeof(string));
            BOMLines.Columns.Add("KumasEni", typeof(decimal));

            ((RepositoryItemGridLookUpEdit)gleCustomer.Edit).TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            gleCustomer.Edit.Assign(RI(Rp.V_Customer));
            gleCustomer.EditValue = 449;

            gridView1.Init("GetPastalBM", gleCustomer.EditValue.ToInt());
            gridView1.AddDetailGrid(gridView2, "PastalBMId");

            gridView2.AddColumn("isPastalLine", typeof(int), "IIF(SipKes=3,1,0)");
            gridView1.AddColumn("QtyNeeded", typeof(decimal), "Total*OrtBM");
            gridView1.AddColumn("PastalSatırı", typeof(int), "SUM(Child({FK}).isPastalLine)");
            gridView1.YanYanaGetirSagina("OrtBM", "QtyNeeded");
            gridView1.YanYanaGetirSoluna("Color", "Artikel");
            if (!ytk(245))
                gridView1.MakeReadOnly();

            gridView1.MakeColumnInvisible("PastalBMId", "Dagilim", "PLU", "Scan", "ProductId", "DosyaAdi", "OrderName", "Aciklama2");
            gridView2.MakeColumnInvisible("PastalBMLinesId", "Total", "UserId", "InsertedOn", "isPastalLine");
            gridView1.Columns["InsertedOn"].VisibleIndex = 0;


            gridView2.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            gridView2.Columns["SipKes"].ColumnEdit = GetCustomRI("Tür", true, "Sipariş Adedi", "Kesilen Adet", "Pastal");
            gridView2.Columns["SipKes"].Caption = "Tür";

            gridView1.FormatAsNumber(0, "Total", "PastalSatırı", "KumasEni");
            gridView1.FormatAsNumber(1, "QtyNeeded");
            gridView1.FormatAsNumber(3, "OrtBM");
            gridView1.AddSummary("Total", "QtyNeeded");
            gridView2.AddSummary();

            btnProcess.ItemClick += btnProcess_ItemClick;
            btnSave.ItemClick += btnSave_ItemClick;
            btnSave.Visibility = ytk(252) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;

            gleCustomer.EditValueChanged += gleCustomer_EditValueChanged;

            splitContainerControl1.AutoSize();
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
            gridView1_FocusedRowChanged(null, null);

            gridView1.AddAutoIncrementalPK("PastalBMId");
            gridView2.AddAutoIncrementalPK("PastalBMLinesId");
            gridView2.DataTable().TableNewRow += PastalBM_TableNewRow;
            gridView2.ShowingEditor += gridView2_ShowingEditor;
            gridView2.RowStyle += gridView2_RowStyle;

            if (ytk(252))
                gridView2.EnableRowDelete();

            if (!ytk(224))
                gleCustomer.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            if (!ytk(237))
                btnProcess.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            gridView2.OptionsView.EnableAppearanceEvenRow = gridView2.OptionsView.EnableAppearanceOddRow = false;
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
        }

        void gridView2_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = !(
                ytk(221) &&
                (gridView2.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle || gridView2.GetFocusedDataRow()["SipKes"].ToInt() == 3) &&
                (gridView2.FocusedColumn.FieldName.StartsWith("A") || gridView2.FocusedColumn.FieldName == "PBoy"));
        }

        void PastalBM_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["SipKes"] = 3;
        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridView1.GetFocusedDataRow() != null)
            {
                string Dagilim = gridView1.GetFocusedDataRow()["Dagilim"].ToStr();
                int ix = 0;
                foreach (string col in Dagilim.Split(",".ToCharArray()))
                    if (ix < 15)
                        if (col != string.Empty)
                            gridView2.Columns[string.Format("A{0:00}", ++ix)].Caption = col;

                for (int i = ix + 1; i < 15; i++)
                {
                    string col = string.Format("A{0:00}", i);
                    gridView2.Columns[col].Caption = " ";
                }

                gridView2.ShowOnlyNonblankColumns();
                gridView2.YanYanaGetirSagina("SipKes", "PBoy", "PKat");
                gridView2.BestFitColumns();
            }
        }

        void gleCustomer_EditValueChanged(object sender, EventArgs e)
        {
            btnProcess.Enabled = gleCustomer.EditValue.ToInt() > 0;

            gridView1.RefreshDataSource("GetPastalBM", gleCustomer.EditValue.ToInt());
            gridView1.BestFitColumns();
            gridView1_FocusedRowChanged(null, null);
        }

        void FileDone(DataSet ds, string FileName)
        {
            string OrderName = string.Empty;
            int StartLine = 0;
            int CustomerId = gleCustomer.EditValue.ToInt();
            switch (CustomerId)
            {
                case 232: OrderName = "."; StartLine = 1; break;
                case 323:
                case 449:
                case 353: 
                case 510: StartLine = 1; break;
                case 447: StartLine = 2; break;
                default: OrderName = "."; break;
            }


            foreach (DataTable dt in ds.Tables)
            {
                int size = 0;
                DataRowCollection rows = dt.Rows;
                DataColumnCollection cols = dt.Columns;

                Dictionary<string, int> indexes = new Dictionary<string, int>();
                List<string> sizes = new List<string>();

                DataRow dr0 = dt.Rows[StartLine];
                for (int colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
                {
                    string col = dr0[colIndex].ToString();
                    switch (CustomerId)
                    {
                        case 56:   //PEUTEREY
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "BEDEN KUMAŞ YÖN": indexes.Add("KumasYonu", colIndex); break;
                                case "COL": indexes.Add("Color", colIndex); break;
                                case "ARTICLE": indexes.Add("Artikel", colIndex); break;
                                case "TOT": indexes.Add("Total", colIndex); break;
                                case "ÜRETİCİ": indexes.Add("Uretici", colIndex); break;
                                case "BEDEN KUMAŞ ENİ 3CM ÇIKILMIŞ HALİ": indexes.Add("KumasEni", colIndex); break;

                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 73:   //MCS
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "AÇIKLAMA": indexes.Add("Aciklama", colIndex); break;
                                case "RENK": indexes.Add("Color", colIndex); break;
                                case "ARTİKEL": indexes.Add("Artikel", colIndex); break;
                                case "TOPLAM": indexes.Add("Total", colIndex); break;
                                case "ÜRETİCİ": indexes.Add("Uretici", colIndex); break;

                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 449:   //KENT&CURWEN
                            switch (col)
                            {
                                case "Product Style No.": indexes.Add("Model", colIndex); break;
                                case "DESCRIZIONE": indexes.Add("Aciklama", colIndex); break;
                                case "PLU No.": indexes.Add("PLU", colIndex); break;
                                case "Color No.": indexes.Add("Color", colIndex); break;
                                case "Müşteri Kodu": indexes.Add("Artikel", colIndex); break;
                                case "Grand Total": indexes.Add("Total", colIndex); break;
                                case "BEDEN KUMAŞ YÖN": indexes.Add("KumasYonu", colIndex); break;

                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 390:   //NETWORK
                            switch (col)
                            {
                                case "model": indexes.Add("Model", colIndex); break;
                                case "YAKA AÇIKLAMA": indexes.Add("Aciklama", colIndex); break;
                                case "key": indexes.Add("Color", colIndex); break;
                                case "firma": indexes.Add("Uretici", colIndex); break;
                                case "artikel": indexes.Add("Artikel", colIndex); break;
                                case "toplam": indexes.Add("Total", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 55:   //PETER MILLAR
                            switch (col)
                            {
                                //case "MÜŞTERİ": indexes.Add("Musteri", colIndex); break;
                                case "LINE": indexes.Add("Model", colIndex); break;
                                case "ARTİKEL KODU": indexes.Add("Artikel", colIndex); break;
                                case "RENK": indexes.Add("Color", colIndex); break;
                                case "ÜRETİCİ": indexes.Add("Uretici", colIndex); break;
                                case "Adet": indexes.Add("Total", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 232:   //GANT
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "ARTİKEL": indexes.Add("Artikel", colIndex); break;
                                case "RENK": indexes.Add("Color", colIndex); break;
                                case "TOP": indexes.Add("Total", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 122:   //DIESEL SPA
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "ARTİKEL": indexes.Add("Artikel", colIndex); break;
                                case "RENK": indexes.Add("Color", colIndex); break;
                                case "BEDEN KUMAŞ YÖN": indexes.Add("Aciklama", colIndex); break;
                                case "TOPLAM": indexes.Add("Total", colIndex); break;
                                case "ÜRETİCİ": indexes.Add("Uretici", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 431: //FAÇONNABLE
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "BEDEN KUMAŞ KODU": indexes.Add("Artikel", colIndex); break;
                                case "MODEL RENK": indexes.Add("Color", colIndex); break;
                                case "BEDEN KUMAŞ  RAPORU":
                                case "BEDEN KUMAŞ RAPORU": indexes.Add("Aciklama", colIndex); break;
                                case "Toplam": indexes.Add("Total", colIndex); break;
                                case "ÜRETİCİ": indexes.Add("Uretici", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 338: //ISCOMPANY
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "ARTICLE": indexes.Add("Artikel", colIndex); break;
                                case "COL": indexes.Add("Color", colIndex); break;
                                //case "BEDEN KUMAŞ RAPORU": indexes.Add("Aciklama", colIndex); break;
                                case "TOT": indexes.Add("Total", colIndex); break;
                                case "ÜRETİCİ": indexes.Add("Uretici", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 366: //ZEGNA
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "ARTİKEL": indexes.Add("Artikel", colIndex); break;
                                case "RENK": indexes.Add("Color", colIndex); break;
                                case "AÇIKLAMA": indexes.Add("Aciklama", colIndex); break;
                                case "TOPLAM": indexes.Add("Total", colIndex); break;
                                case "ÜRETİCİ": indexes.Add("Uretici", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 323: //BEYMEN CLUB
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "KUMAŞ ARTİKELİ": indexes.Add("Artikel", colIndex); break;
                                case "RENK": indexes.Add("Color", colIndex); break;
                                case "AÇIKLAMA": indexes.Add("Aciklama", colIndex); break;
                                case "TOTAL": indexes.Add("Total", colIndex); break;
                                case "KUMAŞ ÜRETİCİSİ": indexes.Add("Uretici", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 353: //TED BAKER
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "KUMAS KODU": indexes.Add("Artikel", colIndex); break;
                                case "RENK": indexes.Add("Color", colIndex); break;
                                case "AÇIKLAMA": indexes.Add("Aciklama", colIndex); break;
                                case "TOPLAM": indexes.Add("Total", colIndex); break;
                                case "KUMASCI": indexes.Add("Uretici", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 355: //INCOM SPA
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "ARTICLE": indexes.Add("Artikel", colIndex); break;
                                case "COL": indexes.Add("Color", colIndex); break;
                                case "AÇIKLAMA": indexes.Add("Aciklama", colIndex); break;
                                case "TOT": indexes.Add("Total", colIndex); break;
                                case "ÜRETİCİ": indexes.Add("Uretici", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 447: //LEE
                            switch (col)
                            {
                                case "model ismi": indexes.Add("Model", colIndex); break;
                                case "artikel": indexes.Add("Artikel", colIndex); break;
                                case "renk": indexes.Add("Color", colIndex); break;
                                case "AÇIKLAMA": indexes.Add("Aciklama", colIndex); break;
                                case "toplam sipariş adedi": indexes.Add("Total", colIndex); break;
                                case "üretici": indexes.Add("Uretici", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        case 510: //MARC O'POLO
                            switch (col)
                            {
                                case "MODEL": indexes.Add("Model", colIndex); break;
                                case "KUMAS KODU": indexes.Add("Artikel", colIndex); break;
                                case "COLOR CODE": indexes.Add("Color", colIndex); break;
                                case "AÇIKLAMA": indexes.Add("Aciklama", colIndex); break;
                                case "TOPLAM": indexes.Add("Total", colIndex); break;
                                case "KUMASCI": indexes.Add("Uretici", colIndex); break;
                                case "KUMAS": indexes.Add("KumasEni", colIndex); break;
                                case "*": size = 1 - size; break;
                                default:
                                    if (size > 0)
                                    {
                                        sizes.Add(dr0[colIndex].ToString());
                                        indexes.Add(string.Format("A{0:00}", size++), colIndex);
                                    }
                                    break;
                            }
                            break;

                        
                    }
                }


                if (OrderName == string.Empty)
                    OrderName = dt.Rows[0][0].ToStr();

                for (int i = StartLine + 1; i < dt.Rows.Count; i++)
                {
                    DataRow dr = rows[i];
                    if (dr[indexes["Model"]].ToStr() != string.Empty)
                    {
                        DataRow drBOMLines = BOMLines.NewRow();
                        drBOMLines["OrderName"] = OrderName;
                        drBOMLines["Dagilim"] = string.Join(",", sizes);
                        drBOMLines["DosyaAdi"] = Path.GetFileName(FileName);

                        foreach (KeyValuePair<string, int> entry in indexes)
                            drBOMLines[entry.Key] = dr[indexes[entry.Key]];

                        BOMLines.Rows.Add(drBOMLines);
                    }
                }
            }

        }


        void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (((GridView)sender).GetRowCellValue(e.RowHandle, "SipKes").ToInt() == 1)
                e.Appearance.BackColor = System.Drawing.Color.LightBlue;
            else
                e.Appearance.Combine((e.RowHandle & 1) != 0 ? gridView2.Appearance.EvenRow : gridView2.Appearance.OddRow);
        }

        void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            gridView2.EndEditing();

            gridView1.Update("", "PastalBM");
            gridView2.Update("", "PastalBMLines");
            gridView1.RefreshDataSource("GetPastalBM", gleCustomer.EditValue.ToInt());

            SetPKat();

            gridView1.EndEditing();
            gridView2.EndEditing();

            gridView1.Update("", "PastalBM");
            gridView2.Update("", "PastalBMLines");
            gridView1.RefreshDataSource("GetPastalBM", gleCustomer.EditValue.ToInt());
        }

        public static DataSet ReadExcel(FileInfo file)
        {
            IWorkbook Workbook = SpreadsheetGear.Factory.GetWorkbook(file.FullName);
            return Workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.NoColumnHeaders | SpreadsheetGear.Data.GetDataFlags.NoColumnTypes);
        }

        void btnProcess_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                using (OpenFileDialog fdOpen = new OpenFileDialog())
                {
                    fdOpen.Filter = "Excel Files (*.xls*)|*.xls*";
                    //fdOpen.Filter = "Excel Files|*.xls*|CSV files|*.csv";
                    fdOpen.FilterIndex = 1;
                    fdOpen.Multiselect = true;
                    if (fdOpen.ShowDialog(AppSession.MainForm) == DialogResult.OK)
                    {
                        //if (ProcessStart != null)
                        //    ProcessStart();

                        //int i = 0;
                        DataSet ds = new DataSet();
                        foreach (string FileName in fdOpen.FileNames)
                        {
                            foreach (DataTable dt in ReadExcel(new FileInfo(FileName)).Tables)
                            {
                                switch (gleCustomer.EditValue.ToInt())
                                {
                                    case 56:   //PEUTEREY
                                        //if (dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 73:   //MCS
                                        if (dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 449:   //KENT&CURWEN
                                        //if (dt.TableName == "Beden Dağılımı")
                                        ds.Tables.Add(dt.Copy());
                                        break;

                                    case 390:   //NETWORK
                                        if (dt.TableName == "Sheet1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 55:   //PETER MILLAR
                                        if (dt.TableName == "Birim Metraj Formu" ||
                                            dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 232:   //GANT
                                        if (dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 122:   //DIESEL SPA
                                        if (dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 431:   //FAÇONNABLE
                                        //if (dt.TableName == "façonnable AW16-17" ||
                                        //    dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 338:   //ISCOMPANY
                                        if (dt.TableName == "Sayfa3")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 366:   //ZEGNA
                                        if (dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 323:   //BEYMEN CLUB
                                        if (dt.TableName == "Sayfa1 (3)")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 353:   //TED BAKER
                                        if (dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 447:   //LEE
                                        if (dt.TableName == "SS17 forecast 08.08")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 355:   //INCOM SPA
                                        if (dt.TableName == "Sayfa3")
                                            ds.Tables.Add(dt.Copy());
                                        break;

                                    case 510:   //MARC O'POLO
                                        if (dt.TableName == "Sayfa1")
                                            ds.Tables.Add(dt.Copy());
                                        break;


                                    default:
                                        ds.Tables.Add(dt.Copy());
                                        break;

                                }
                            }
                        }

                        if (fdOpen.FileNames.Length > 0)
                            FileDone(ds, fdOpen.FileNames[0]);

                        int res = ExecuteScalar("ImportPastalBM", gleCustomer.EditValue.ToInt(), BOMLines.Serialize()).ToInt();
                        if (res > 0)
                        {
                            Notify("Aktarıldı.");
                            gridView1.RefreshDataSource("GetPastalBM", gleCustomer.EditValue.ToInt());
                            gridView1.BestFitColumns();
                            gridView2.BestFitColumns();
                        }
                        else
                            ShowErrorMessage("Bu dosya daha önce aktarılmış.");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                BOMLines.Clear();
                Cursor = Cursors.Default;
            }
        }




        int currentPastalBMId;
        private DataTable dtDagilim
        {
            get
            {
                DataRow[] drs = gridView2.DataTable().Select("PastalBMId=" + currentPastalBMId.ToString() + " AND SipKes=3 AND PBoy>0");
                if (drs.Length > 0)
                    return drs.CopyToDataTable();
                else
                    return null;
            }
        }

        private int SiparisAdedi(string colName)
        {
            if (gridView2.DataTable().Select("PastalBMId=" + currentPastalBMId.ToString() + " AND SipKes=1").Length > 0)
                return gridView2.DataTable().Select("PastalBMId=" + currentPastalBMId.ToString() + " AND SipKes=1")[0][colName].ToInt();
            else
                return 0;
        }

        private void SetPKat()
        {
            gridView1.EndEditing();
            gridView2.EndEditing();

            for (int rowHandle = 0; rowHandle < gridView1.DataRowCount; rowHandle++)
            {
                currentPastalBMId = gridView1.GetRowCellValue(rowHandle, "PastalBMId").ToInt(-1);

                List<string> tekBilinmeyenli = new List<string>();
                List<string> cokBilinmeyenli = new List<string>();
                bool eksikPastal = false;     //dolu beden için hiç pastal girilmediyse

                if (dtDagilim != null)
                {
                    for (int dagilimIndex = 1; dagilimIndex < 16; dagilimIndex++)
                    {
                        string colName = "A" + dagilimIndex.ToString().PadLeft(2, '0');

                        foreach (DataRow drx in gridView2.DataTable().Select("PastalBMId=" + currentPastalBMId))
                            if (drx[colName].ToInt(-1) == 0)
                                drx[colName] = DBNull.Value;

                        int doluPastalAdedi = dtDagilim.Compute("Count(" + colName + ")", "").ToInt(-1);
                        int d = dtDagilim.Compute("Count(" + colName + ")", string.Empty).ToInt(-1);
                        eksikPastal |= (d > 0 && SiparisAdedi(colName) == 0) || (d == 0 && SiparisAdedi(colName) > 0);

                        if (doluPastalAdedi == 1)
                            tekBilinmeyenli.Add(colName);
                        else if (doluPastalAdedi > 1)
                            cokBilinmeyenli.Add(colName);
                    }

                    foreach (string colName in tekBilinmeyenli)
                    {
                        DataRow drDagilim = dtDagilim.Select(colName + " is not null")[0];
                        int carpan = drDagilim[colName].ToInt(-1);
                        int pkatMevcut = drDagilim["PKat"].ToInt(-1);
                        int pKat = Convert.ToInt32(Math.Ceiling(SiparisAdedi(colName) / (decimal)carpan));

                        if (pKat > pkatMevcut)
                        {
                            int PastalBMLinesId = drDagilim["PastalBMLinesId"].ToInt();
                            gridView2.DataTable().Select("PastalBMLinesId=" + PastalBMLinesId.ToStr())[0]["PKat"] = pKat;
                        }
                    }

                    List<string> duzeltilen = null;
                    do
                    {
                        duzeltilen = new List<string>();

                        foreach (string colName in cokBilinmeyenli)
                        {
                            DataRow[] bilinmeyen = dtDagilim.Select(colName + " is not null and PKat is null");
                            if (bilinmeyen.Length > 1)
                                continue;

                            if (bilinmeyen.Length == 0)
                            {
                                duzeltilen.Add(colName);
                                continue;
                            }


                            DataRow[] bilinen = dtDagilim.Select(colName + " is not null and PKat is not null");

                            int kapsanan = 0;
                            foreach (DataRow drDagilim in bilinen)
                            {
                                int pKat = drDagilim["PKat"].ToInt(-1);
                                int carpan = drDagilim[colName].ToInt(-1);
                                kapsanan += pKat * carpan;
                            }

                            int eklenecek = SiparisAdedi(colName) - kapsanan;

                            if (eklenecek < 0)
                                eklenecek = 0;

                            DataRow drBilinmeyen = bilinmeyen[0];
                            int PastalBMLinesId = drBilinmeyen["PastalBMLinesId"].ToInt(-1);
                            int carpanBilinmeyen = drBilinmeyen[colName].ToInt(-1);

                            gridView2.DataTable().Select("PastalBMLinesId=" + PastalBMLinesId.ToStr())[0]["PKat"] = eklenecek / carpanBilinmeyen;
                            duzeltilen.Add(colName);
                        }

                        foreach (string duzgun in duzeltilen)
                            cokBilinmeyenli.Remove(duzgun);

                    }
                    while (duzeltilen.Count > 0 &&
                        cokBilinmeyenli.Count > 0);

                    eksikPastal |= cokBilinmeyenli.Count > 0;
                }

                if (eksikPastal)
                {
                    DataRow[] drt = gridView1.DataTable().Select("PastalBMId=" + currentPastalBMId.ToString(), string.Empty);
                    if (drt.Length == 1)
                        gridView1.DataTable().Select("PastalBMId=" + currentPastalBMId.ToString(), string.Empty)[0]["OrtBM"] = DBNull.Value;
                }
                else
                {
                    int toplam = 0;
                    DataRow[] drs = gridView2.DataTable().Select("PastalBMId=" + currentPastalBMId.ToString() + " AND SipKes=3 and PKat is not null");
                    for (int dagilimIndex = 1; dagilimIndex < 16; dagilimIndex++)
                    {
                        string colName = "A" + dagilimIndex.ToString().PadLeft(2, '0');
                        foreach (DataRow drDagilim in drs)
                            if (drDagilim[colName].ToInt(-1) > 0)
                                toplam += drDagilim[colName].ToInt(-1) * drDagilim["PKat"].ToInt(-1);
                    }

                    decimal uzunluk = 0;
                    foreach (DataRow dr in drs)
                        uzunluk += decimalParse(dr["PKat"]) * (decimalParse(dr["PBoy"]) + 0.04m);

                    if (toplam > 0 && uzunluk > 0)
                        MetrajEkle(currentPastalBMId, uzunluk / toplam);
                }
            }
        }

        void MetrajEkle(int PastalBMId, decimal Metraj)
        {
            DataRow[] drs = gridView1.DataTable().Select("PastalBMId=" + currentPastalBMId.ToString(), string.Empty);
            if (drs.Length == 1)
                gridView1.DataTable().Select("PastalBMId=" + currentPastalBMId.ToString(), string.Empty)[0]["OrtBM"] = (float)Metraj;
        }

    }
}
